package com.ssm.plus.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ssm.plus.entity.User;
import com.ssm.plus.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    IUserService userService;

    @GetMapping("/")
    public List<User> list(@RequestParam(required = false, defaultValue = "") String username, @RequestParam(required = false, defaultValue = "") String type) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(username)) {
            wrapper.eq("username", username);
        }
        if (!StringUtils.isEmpty(type)) {
            wrapper.eq("type", type);
        }
        return userService.list(wrapper);
    }

    @GetMapping("/login")
    public User login(@RequestParam String username, @RequestParam String password, @RequestParam String type) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        wrapper.eq("password", password);
        wrapper.eq("type", type);
        return userService.getOne(wrapper, false);
    }

    @GetMapping("/login2")
    public User login2(@RequestParam String username, @RequestParam String password) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        wrapper.eq("password", password);
        return userService.getOne(wrapper, false);
    }

    @GetMapping("/page")
    public Page<User> page(@RequestParam(required = false, defaultValue = "1") Integer number,
                           @RequestParam(required = false, defaultValue = "") String username,
                           @RequestParam(required = false, defaultValue = "") String type) {
        Page<User> page = new Page<>(number, 10);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(username)) {
            wrapper.eq("username", username);
        }
        if (!StringUtils.isEmpty(type)) {
            wrapper.eq("type", type);
        }
        return userService.page(page, wrapper);
    }

    @PostMapping("/")
    public Object save(@RequestBody User user) {
        return userService.saveOrUpdate(user);
    }

    @GetMapping("/{id}")
    public Object get(@PathVariable Long id) {
        return userService.getById(id);
    }

    @DeleteMapping("/{id}")
    public Object delete(@PathVariable Long id) {
        return userService.removeById(id);
    }
}
